//
//  ShareView.m
//  quanminzhekou
//
//  Created by zxl on 15/1/8.
//  Copyright (c) 2015年 zhongqinglongtu. All rights reserved.
//

#import "ShareView.h"
#import "UMSocial.h"
#import "ViewWithButtonAndLable.h"
#import "../ThirdParty/UMSocial_Sdk_Extra_Frameworks/TencentOpenAPI/UMSocialQQHandler.h"
#import "../ThirdParty/UMSocial_Sdk_Extra_Frameworks/Wechat/WXApi.h"

#define ShareTitle @"我在全民打折网发现了一个超值商品，全场包邮，请速来围观哦~"

@interface ShareView () <UMSocialUIDelegate, UIAlertViewDelegate>
@property (nonatomic, strong) NSMutableArray* shareModelsArr;

@property (nonatomic, strong) UIButton* cancelBtn;
@property (nonatomic, strong) UIView* line;

@end

@implementation ShareView

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelBtn.translatesAutoresizingMaskIntoConstraints = NO;
        _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:20];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(onTapCancelBtn:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_cancelBtn];
        
        NSArray* cancelBtn_constraints_H = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_cancelBtn]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_cancelBtn)];
        NSArray* cancelBtn_constraints_V = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[_cancelBtn(==43)]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_cancelBtn)];
        [self addConstraints:cancelBtn_constraints_H];
        [self addConstraints:cancelBtn_constraints_V];
        
        _line = [[UIView alloc] init];
        _line.translatesAutoresizingMaskIntoConstraints = NO;
        _line.backgroundColor = [UIColor lightGrayColor];
        [self addSubview:_line];
        
        NSArray* line_constraints_H = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_line]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_line)];
        NSArray* line_constraints_V = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[_line(==1)]-0-[_cancelBtn]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_line, _cancelBtn)];
        [self addConstraints:line_constraints_H];
        [self addConstraints:line_constraints_V];
        
    }
    
    return self;
}

- (void)setupShareModelsArr {
    if ([self.shareModelsArr isKindOfClass:[NSMutableArray class]]) {
        for (UIView* view in self.subviews) {
            if ([view isKindOfClass:[ViewWithButtonAndLable class]]) {
                [view removeFromSuperview];
            }
        }
        [self.shareModelsArr removeAllObjects];
    } else {
        self.shareModelsArr = [NSMutableArray new];
    }
    
    
    NSString* titleStr = nil;
    NSString* imgStrForBtnNormal = nil;
    NSString* imgStrForBtnHighlight = nil;
    ShareModelType modelType;
    for (NSInteger index = 0; index < 6; ++index) {
        switch (index) {
            case 0:
                if ([WXApi isWXAppInstalled]) {
                    titleStr = @"微信";
                    imgStrForBtnNormal = @"share_wechat";
                    modelType = ShareModelTypeOfWechat;
                } else {
                    continue;
                }
                break;
                
            case 1:
                if ([WXApi isWXAppInstalled]) {
                    titleStr = @"朋友圈";
                    imgStrForBtnNormal = @"share_timeline";
                    modelType = ShareModelTypeOfTimeline;
                } else {
                    continue;
                }
                break;
                
            case 2:
                if ([QQApi isQQInstalled]) {
                    titleStr = @"QQ好友";
                    imgStrForBtnNormal = @"share_qq_friend";
                    modelType = ShareModelTypeOfQQFriend;
                } else {
                    continue;
                }
                break;
                
            case 3:
                if ([QQApi isQQInstalled]) {
                    titleStr = @"QQ空间";
                    imgStrForBtnNormal = @"share_zone";
                    modelType = ShareModelTypeOfQQzone;
                } else {
                    continue;
                }
                break;
                
            case 4:
                titleStr = @"新浪微博";
                imgStrForBtnNormal = @"share_sina";
                modelType = ShareModelTypeOfSinaWeibo;
                break;
                
            default:
                titleStr = @"短信";
                imgStrForBtnNormal = @"share_message";
                modelType = ShareModelTypeOfSystemMessage;
                break;
        }
        
        ShareModel* model = [[ShareModel alloc] init];
        model.titleStr = titleStr;
        model.imgStrForBtnNormal = imgStrForBtnNormal;
        model.imgStrForBtnHighlight = imgStrForBtnHighlight;
        model.modelType = modelType;
        [self.shareModelsArr addObject:model];
    }
    
    self.frame = CGRectMake(0, CGRectGetHeight([UIScreen mainScreen].bounds), CGRectGetWidth([UIScreen mainScreen].bounds), self.shareModelsArr.count > 4 ? (60 + 10) * 2 + 10 + 43 : (60 + 10 + 10 + 43));
    
    [self setupShareAllButtons];
}

#pragma mark - 
- (void)setupShareAllButtons {
    CGFloat spacing = (CGRectGetWidth(self.frame) - 60 * 4) / 5.0;
    
    for (NSInteger index = 0; index < self.shareModelsArr.count; ++index) {
        ShareModel* model = [self.shareModelsArr objectAtIndex:index];
        ViewWithButtonAndLable* view = [[ViewWithButtonAndLable alloc] initWithFrame:CGRectMake((index % 4) * (spacing + 60) + spacing, index / 4 * (10 + 60) + 10, 60, 60) shareModel:model];
        
        __weak typeof(self) weakSelf = self;
        view.tapButtonHandler = ^() {
            switch (model.modelType) {
                case ShareModelTypeOfWechat:
                    [weakSelf onTapWeChatBtn:nil];
                    break;
                    
                case ShareModelTypeOfTimeline:
                    [weakSelf onTapTimeLineBtn:nil];
                    break;
                    
                case ShareModelTypeOfQQFriend:
                    [weakSelf onTapQQFriendBtn:nil];
                    break;
                    
                case ShareModelTypeOfQQzone:
                    [weakSelf onTapQQZoneBtn:nil];
                    break;
                    
                case ShareModelTypeOfSinaWeibo:
                    [weakSelf onTapSinaWeiboBtn:nil];
                    break;
                    
                default:
                    [weakSelf onTapMessageBtn:nil];
                    break;
            }
        };
        
        [self addSubview:view];
    }
}

- (void)showShareAlertViewWithShareTypeTitle:(NSString*)titleStr andShareMessage:(NSString*)messageStr {
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:titleStr message:messageStr delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
    [alertView show];
}

#pragma mark - IBAction
- (IBAction)onTapCancelBtn:(id)sender {
    if (self.tapCancelHandler) {
        self.tapCancelHandler();
    }
}

- (IBAction)onTapWeChatBtn:(id)sender {
    [self onTapCancelBtn:nil];
    
    [UMSocialData defaultData].extConfig.wechatSessionData.title = ShareTitle;
    [UMSocialData defaultData].extConfig.wechatSessionData.url = self.currentGoodsViewModel.shareUrl;
    UIImage* image = [UIImage imageWithData:[NSData dataWithContentsOfURL:self.currentGoodsViewModel.imgUrl]];
    
    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatSession] content:self.currentGoodsViewModel.titleStr image:image location:nil urlResource:nil presentedController:self.ownedController completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            [self showShareAlertViewWithShareTypeTitle:@"微信好友" andShareMessage:@"分享成功！"];
        } else if (response.responseCode != UMSResponseCodeCancel) {
            [self showShareAlertViewWithShareTypeTitle:@"微信好友" andShareMessage:@"分享失败！"];
        }
    }];
}

- (IBAction)onTapTimeLineBtn:(id)sender {
    [self onTapCancelBtn:nil];
    
    [UMSocialData defaultData].extConfig.wechatTimelineData.title = ShareTitle;
    [UMSocialData defaultData].extConfig.wechatTimelineData.url = self.currentGoodsViewModel.shareUrl;
    UIImage* image = [UIImage imageWithData:[NSData dataWithContentsOfURL:self.currentGoodsViewModel.imgUrl]];
    
    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatTimeline] content:self.currentGoodsViewModel.titleStr image:image location:nil urlResource:nil presentedController:self.ownedController completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            [self showShareAlertViewWithShareTypeTitle:@"微信朋友圈" andShareMessage:@"分享成功！"];
        } else if (response.responseCode != UMSResponseCodeCancel) {
            [self showShareAlertViewWithShareTypeTitle:@"微信朋友圈" andShareMessage:@"分享失败！"];
        }
    }];
}

- (IBAction)onTapQQFriendBtn:(id)sender {
    [self onTapCancelBtn:nil];
    
    [UMSocialData defaultData].extConfig.qqData.url = self.currentGoodsViewModel.shareUrl;
    [UMSocialData defaultData].extConfig.qqData.title = ShareTitle;
    
    UIImage* image = [UIImage imageWithData:[NSData dataWithContentsOfURL:self.currentGoodsViewModel.imgUrl]];
    
    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToQQ] content:self.currentGoodsViewModel.titleStr image:image location:nil urlResource:nil presentedController:self.ownedController completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            [self showShareAlertViewWithShareTypeTitle:@"QQ好友" andShareMessage:@"分享成功！"];
        } else if (response.responseCode != UMSResponseCodeCancel) {
            [self showShareAlertViewWithShareTypeTitle:@"QQ好友" andShareMessage:@"分享失败！"];
        }
    }];
}

- (IBAction)onTapQQZoneBtn:(id)sender {
    [self onTapCancelBtn:nil];
    
    [UMSocialData defaultData].extConfig.qzoneData.url = self.currentGoodsViewModel.shareUrl;
    [UMSocialData defaultData].extConfig.qzoneData.title = ShareTitle;
    
    UIImage* image = [UIImage imageWithData:[NSData dataWithContentsOfURL:self.currentGoodsViewModel.imgUrl]];
    
    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToQzone] content:self.currentGoodsViewModel.titleStr image:image location:nil urlResource:nil presentedController:self.ownedController completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            [self showShareAlertViewWithShareTypeTitle:@"QQ空间" andShareMessage:@"分享成功！"];
        } else if (response.responseCode != UMSResponseCodeCancel) {
            [self showShareAlertViewWithShareTypeTitle:@"QQ空间" andShareMessage:@"分享失败！"];
        }
    }];
}

- (IBAction)onTapSinaWeiboBtn:(id)sender {
    [self onTapCancelBtn:nil];
    
    UIButton* btn = (UIButton*)sender;
    btn.enabled = NO;
    
    NSString* content = [NSString stringWithFormat:@"%@ %@", self.currentGoodsViewModel.titleStr, self.currentGoodsViewModel.shareUrl];
    UIImage* image = [UIImage imageWithData:[NSData dataWithContentsOfURL:self.currentGoodsViewModel.imgUrl]];
    
    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToSina] content:content image:image location:nil urlResource:nil presentedController:self.ownedController completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            [self showShareAlertViewWithShareTypeTitle:@"新浪微博" andShareMessage:@"分享成功！"];
        } else if (response.responseCode != UMSResponseCodeCancel) {
            [self showShareAlertViewWithShareTypeTitle:@"新浪微博" andShareMessage:@"分享失败！"];
        }
        
        btn.enabled = YES;
    }];
}

- (IBAction)onTapMessageBtn:(id)sender {
    [self onTapCancelBtn:nil];
    
    NSString* content = [NSString stringWithFormat:@"%@ %@", self.currentGoodsViewModel.titleStr, self.currentGoodsViewModel.shareUrl];
    
    [[UMSocialControllerService defaultControllerService] setShareText:content shareImage:nil socialUIDelegate:self];
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:@"sms"];
    snsPlatform.snsClickHandler(self.ownedController, [UMSocialControllerService defaultControllerService], YES);
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (0 == buttonIndex) {
        if ([alertView.title isEqualToString:@"微信好友"]) {
//            self.weChatBtn.enabled = YES;
        } else if ([alertView.title isEqualToString:@"微信朋友圈"]) {
//            self.timeLineBtn.enabled = YES;
        } else if ([alertView.title isEqualToString:@"QQ好友"]) {
//            self.qqFriendBtn.enabled = YES;
        } else if ([alertView.title isEqualToString:@"QQ空间"]) {
//            self.qqZoneBtn.enabled = YES;
        } else if ([alertView.title isEqualToString:@"新浪微博"]) {
//            self.sinaWeiboBtn.enabled = YES;
        }
    }
}

@end
